
//  Created by 小柠檬🍋 on 2025/9/7.
//

import SwiftUI

//新建api
struct AiCustomCreateView: View {
    @StateObject var viewModel = AiCustomCreateViewModel()
    @State private var showDelAiDialog = false //删除回应
    
    @State var name = ""
    @State var host = ""
    @State var token = ""
    @State var model = ""
    @State var url = ""
    var bean : AiCustomBean
    
    var body: some View {
        VStack(alignment : .leading, spacing: 0){
            if !userManager.isVip() {
                Text("该功能是需要开通Pro才能连接API")
                    .font(.system(size: 12))
                    .foregroundColor(.bgTipsText)
                    .frame(maxWidth: .infinity, alignment: .leading)
                    .padding(.horizontal, 20)
                    .padding(.vertical, 5)
                    .background(.bgTips)
                    .padding(.top, 1)
            }
            //内容
            ScrollView {
                Text(highlightAndBoldText(fullText: "名称", boldTexts: ["名称"], size: 12))
                    .font(.system(size: 12))
                    .foregroundColor(.bgNormalText4)
                    .frame(maxWidth: .infinity, alignment: .leading)
                customTextEditor(
                    text: $name,
                    hint: "请输名称(限制20个字)", // 自定义提示文字
                    maxCount: 20 // 自定义最大字数
                )
                Color.clear.frame(height: 15)
                Text(highlightAndBoldText(fullText: "API地址(注：非网站地址，如果是一些中转站请留意是否需添加 v1/chat/completions)", boldTexts: ["API地址"], size: 12))
                    .font(.system(size: 12))
                    .foregroundColor(.bgNormalText4)
                    .frame(maxWidth: .infinity, alignment: .leading)
                customTextEditor(
                    text: $host,
                    hint: "请输入API地址", // 自定义提示文字
                    maxCount: 1000 // 自定义最大字数
                )
                Color.clear.frame(height: 15)
                Text(highlightAndBoldText(fullText: "令牌（密钥）", boldTexts: ["令牌（密钥）"], size: 12))
                    .font(.system(size: 12))
                    .foregroundColor(.bgNormalText4)
                    .frame(maxWidth: .infinity, alignment: .leading)
                customTextEditor(
                    text: $token,
                    hint: "请输入令牌（密钥）", // 自定义提示文字
                    maxCount: 1000 // 自定义最大字数
                )
                Color.clear.frame(height: 15)
                Text(highlightAndBoldText(fullText: "模型名称（参考网站的模型名称，不可随意填写）", boldTexts: ["模型名称"], size: 12))
                    .font(.system(size: 12))
                    .foregroundColor(.bgNormalText4)
                    .frame(maxWidth: .infinity, alignment: .leading)
                customTextEditor(
                    text: $model,
                    hint: "请输入模型名称", // 自定义提示文字
                    maxCount: 1000 // 自定义最大字数
                )
                Color.clear.frame(height: 15)
                Text(highlightAndBoldText(fullText: "网站地址，用于方便跳转（可选）", boldTexts: ["网站地址"], size: 12))
                    .font(.system(size: 12))
                    .foregroundColor(.bgNormalText4)
                    .frame(maxWidth: .infinity, alignment: .leading)
                customTextEditor(
                    text: $url,
                    hint: "请输入网站地址", // 自定义提示文字
                    maxCount: 1000 // 自定义最大字数
                )
                Color.clear.frame(height: 5)
                Text("查看 API 站点")
                    .font(.system(size: 12))
                    .foregroundColor(themeManager.themeColor)
                    .padding(.vertical, 5)
                    .frame(maxWidth: .infinity, alignment: .leading)
                    .onTapGesture {
                        pathManager.jump(type: JumpType.AI_API_SITES)
                    }
                Color.clear.frame(height: 20)
                ZStack{
                    Text("保存")
                        .foregroundColor(themeManager.themeColor)
                        .font(.system(size: 16))
                        .padding(.horizontal,10)
                        .padding(.vertical,15)
                        .frame(width: 300)
                        .background(themeManager.themeColor.opacity(0.1))
                        .cornerRadius(8)
                        .contentShape(Rectangle())
                        .onTapGesture {
                            viewModel.doSave(bean: bean) {
                                pathManager.back()
                            }
                        }
                    Spacer()
                }
            }.padding(.horizontal, 20)
                .padding(.vertical, 20)
        }.navigationTitle("新建API连接")
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .background(.bgWhite)
            .toolbar {
                // 添加一个右标题按钮
                if bean.objectId?.isEmpty == false {
                    ToolbarItem(placement: .navigationBarTrailing) {
                        Text("删除")
                            .foregroundColor(.bgDel)
                            .font(.system(size: 12))
                            .padding(.horizontal,10)
                            .padding(.vertical,7)
                            .cornerRadius(8)
                            .contentShape(Rectangle())
                            .onTapGesture {
                                showDelAiDialog = true
                            }
                    }
                }
            }.onChange(of: name) { newValue in
                bean.name = newValue
            }.onChange(of: host) { newValue in
                bean.host = newValue
            }.onChange(of: token) { newValue in
                bean.token = newValue
            }.onChange(of: model) { newValue in
                bean.model = newValue
            }.onChange(of: url) { newValue in
                bean.url = newValue
            }.alert("温馨提示",isPresented:$showDelAiDialog) {
                Button("取消",role: .cancel){}
                Button("确定删除",role: .destructive) {
                    viewModel.doDel(bean: bean) {
                        pathManager.back()
                    }
                }
            } message: {
                Text("是否确定删除?")
            }.onAppear {
                if !viewModel.isInit {
                    viewModel.isInit = true
                    self.name = bean.name ?? ""
                    self.host = bean.host ?? ""
                    self.token = bean.token ?? ""
                    self.model = bean.model ?? ""
                    self.url = bean.url ?? ""
                }
            }.onDisappear{
                hideKeyboard()
            }.contentShape(Rectangle())
            .onTapGesture {
                hideKeyboard()
            }
    }
}

import SwiftUI

// 为 ApiSitesItemView 扩展带参数的文本编辑功能
extension AiCustomCreateView {
    /// 带 hint 和字数限制的 TextEditor
    /// - Parameters:
    ///   - text: 绑定的输入文本
    ///   - hint: 提示文字
    ///   - maxCount: 最大字数限制
    /// - Returns: 配置好的 TextEditor 视图
    func customTextEditor(
        text: Binding<String>,
        hint: String,
        maxCount: Int
    ) -> some View {
        ZStack(alignment: .center) {
            // 文本编辑器（带字数限制）
            TextField(hint, text: text)
                .font(.system(size: 14))
                .foregroundColor(.bgNormalText)
                .frame(height: 45)
                .padding(.horizontal,10)
                .background(.bgEdit)
                .cornerRadius(8)
                .padding(.top, 8)
                .onChange(of: text.wrappedValue) { newValue in
                    // 限制最大字数
                    if newValue.count > maxCount {
                        text.wrappedValue = String(newValue.prefix(maxCount))
                    }
                }
        }
    }
}

//#Preview {
//    AiCustomCreateView()
//}

//定义预览提供者
struct AiCustomCreateView_Previews: PreviewProvider {
    static var previews: some View {
        //使用预览共享配置
        configurePreviewEnvironment(for: AiCustomCreateView(bean : AiCustomBean()))
    }
}
